<template>
  <div>
    <i-dialog
      :title="title"
      :visible="visible"
      width="642px"
      :close-on-click-modal="false"
      @close="outerClose"
    >
      <i-form
        :items="formItems"
        :model="form"
        ref="form"
        :rules="rules"
        label-width="140px"
        class="demo-form"
      >
        <template slot="batchAdd">
          <el-form-item label="导入" prop="batchData">
            <LoadFile v-model="batchData" ref="loadFile" />
          </el-form-item>
        </template>
      </i-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="outerClose">取 消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </span>
    </i-dialog>
  </div>
</template>
<script>
import formValidate from '@/utils/validate'
import LoadFile from '@/components/LoadFile'
export default {
  name: 'PresentAndEnergy',
  components: { LoadFile },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    items: {
      type: Array,
      default: () => [
        'userMobile',
        'confirmMobile',
        'andEnergyType',
        'andEnergyCardRuleId',
        'energyPoint',
        'andEnergyCardExpire',
        'batchAdd',
      ],
    },
    cardAttr: {
      type: Object,
      default: () => {},
    },
    api: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      batchData: [],
      form: { andEnergyType: 1 },
      allItems: [
        {
          type: 'text',
          value: 'userMobile',
          label: '用户手机号',
          required: true,
        },
        {
          type: 'text',
          value: 'confirmMobile',
          label: '手机号确认',
          required: true,
        },
        {
          type: 'radio',
          value: 'andEnergyType',
          label: '和能量类型',
          required: true,
          options: [
            {
              text: '发售中',
              label: 1,
            },
            {
              text: '自定义和能量',
              label: 2,
            },
          ],
        },
        {
          type: 'select',
          value: 'andEnergyCardRuleId',
          label: '和能量',
          placeholder: '请选择和能量套餐',
          clearable: true,
          required: true,
          ifRender: () => {
            return this.form.andEnergyType === 1
          },
        },
        {
          type: 'inputNumber',
          value: 'energyPoint',
          label: '和能量数量（点）',
          placeholder: '请输入和能量点数（点）',
          min: 1,
          max: 99999,
          ifRender: () => this.form.andEnergyType === 2,
        },
        {
          type: 'inputNumber',
          value: 'andEnergyCardExpire',
          label: '有效期',
          min: 7,
          max: 999,
          placeholder: '请输入和能量套餐有效期，不填则为无限期（天）',
          ifRender: () => this.form.andEnergyType === 2,
        },
        {
          slot: 'batchAdd',
          value: 'batchAdd',
        },
      ],
      rules: {
        mobile: [{ validator: formValidate('validateMobile') }],
        confirmMobile: [
          {
            validator: (rules, value, callback) => {
              if (this.form.userMobile !== this.form.confirmMobile) {
                callback(new Error('电话号码不一致'))
              } else {
                callback()
              }
            },
          },
          {
            validator: formValidate('validateMobile'),
          },
        ],
        // batchData: [
        //   {
        //     validator: (rules, value, callback) => {
        //       if (!Array.isArray(this.batchData) || this.batchData.length < 1) {
        //         callback(new Error('请上传正确的批量赠送表格'))
        //       } else {
        //         callback()
        //       }
        //     },
        //   },
        // ],
      },
    }
  },
  computed: {
    formItems() {
      return this.allItems.filter((item) => this.items.includes(item.value))
    },
    title() {
      return '赠送和能量'
    },
  },
  created() {
    this.form = {
      andEnergyType: 1,
    }
    return this._handleAndEnergyCards('andEnergyRule')
  },
  methods: {
    _handleAndEnergyCards(type) {
      const handler = {
        andEnergyRule: this._andEnergyRuleList,
      }
      return handler[type]()
    },
    _andEnergyRuleList() {
      this.api['andEnergyRule']().then((res) => {
        this.timeCardList = res

        let index = this.allItems.findIndex(
          (item) => item.value === 'andEnergyCardRuleId'
        )
        if (index < 0) return
        let item = this.allItems[index] // staId
        item.options = res.map((item) => {
          return {
            label: `和能量${item.energyAmount}点，${
              item.price / 100
            }元，有效期:${item.effectiveDays ? item.effectiveDays : '无限'}天`,
            value: item.id,
          }
        })
        this.$set(this.allItems, index, item)
      })
    },
    outerOpen() {},
    outerClose() {
      this.form = {
        timeCardType: 1,
      }
      this.$emit('update:visible', false)
    },
    refreshTable() {
      this.$emit('refreshTable')
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = Object.assign(
            {},
            this.form,
            this.cardAttr.mobile && {
              userMobile: this.cardAttr.mobile,
            }
          )
          params.userMobile = this.items.includes('userMobile')
            ? [params.userMobile]
            : params.userMobile
          params.andEnergyType && delete params.andEnergyType
          params.confirmMobile && delete params.confirmMobile
          if (this.items.includes('batchAdd')) {
            if (!Array.isArray(this.batchData) || this.batchData.length < 0) {
              this.$message({
                message: '请上传正确的批量赠送表格',
                type: 'warning',
                showClose: true,
              })
              this.$refs.loadFile.onRemove()

              return
            }

            let phoneArr = []
            let phoneReg = /^1[0-9]{10}$/
            this.batchData.some((item) => {
              if (item['用户手机号']) {
                let phone = item['用户手机号']
                  .toString()
                  .replace(/(^\s*)|(\s*$)/g, '')
                phoneArr.push(phone)
                if (!phoneReg.test(phone)) {
                  this.$message({
                    showClose: true,
                    message: `${phone}, 格式错误请修正！`,
                    type: 'warning',
                  })
                  phoneArr = []
                  return true
                }
              }
            })
            if (phoneArr.length <= 0) {
              this.$message({
                message: '数据导入失败!',
                type: 'error',
                offset: 60,
              })
              this.$refs.loadFile.onRemove()
              return
            }

            params.userMobile = phoneArr
          }
          this.api['submit']({ ...params }).then(
            () => {
              this.$message({
                message: '赠送成功',
                type: 'success',
              })
              this.outerClose()
              this.refreshTable()
            },
            () => {
              this.outerClose()
              this.refreshTable()
            }
          )
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.timecard-item {
  width: 50%;
  display: inline-block;
  .el-input {
    width: 80%;
  }
}
</style>
